package com.jack.lib.ui.widget

import android.content.Context
import androidx.appcompat.widget.AppCompatCheckBox
import android.widget.CompoundButton
import android.content.res.TypedArray
import android.util.AttributeSet
import com.jack.lib.ui.R

/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/11/20 14:29
 */
class JCheckBox @kotlin.jvm.JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : AppCompatCheckBox(context, attrs, defStyleAttr){

    private var mListener: OnCheckedChangeListener? = null
    private var mAutoEvent = false

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.JCheckBox)
        parseAttr(typedArray)
        typedArray.recycle()
    }

    private fun parseAttr(typedArray: TypedArray) {
        mAutoEvent = typedArray.getBoolean(R.styleable.JCheckBox_JAutoEvent, false)
    }

    override fun performClick(): Boolean {
        val handled = super.performClick()
        mListener?.onCheckedChanged(this, isChecked)
        return handled
    }

    override fun setChecked(checked: Boolean) {
        super.setChecked(checked)
        if (!mAutoEvent && mListener != null) {
            mListener!!.onCheckedChanged(this, isChecked)
        }
    }

    fun setOnCheckedListener(listener: OnCheckedChangeListener?) {
        mListener = listener
    }
}